import wepy from 'wepy'

export default class search extends wepy.mixin {
  data = {
    value:'',
    suggestList:[],
    // 搜索节流控制
    setTimeId:0,
    //搜索历史
    searchHistory:[],
    //
  }

  config = {
  }

  onLoad (){
    this.searchHistory = wepy.getStorageSync("searchHistory") || []
  }

  onShow(){
    this.$parent.setTabBarBadge();
  }

  methods = {
    inpChange(e){
      clearTimeout(this.setTimeId)
      this.value = e.detail.trim();
      if(this.value === '')  return this.suggestList = []
      this.setTimeId = setTimeout(async ()=>{
        const res = await wepy.get("/goods/qsearch",{
          query:this.value
        })
        if(res.data.meta.status !== 200) return wepy.baseToast();
        this.suggestList = res.data.message;
        this.$apply();
      },500)
    },

    //输入框敲击回车触发
    onSearch(e){
      if(e.detail.trim() === '') return;
      
      //查看本地数据里是否存在
      const index = this.searchHistory.indexOf(e.detail.trim());
      // 如果不存在 就存进去
      if(index === -1) this.searchHistory.unshift(e.detail.trim());
      //将数组的长度始终保持在10 splice的返回值是删除的元素
      this.searchHistory = this.searchHistory.splice(0,10)
      //将搜索数据存储到本地
      wepy.setStorageSync("searchHistory",this.searchHistory);
      //清除定时器
      clearTimeout(this.setTimeId);
      // 跳转页面 携带参数
      wepy.navigateTo({
        url:"/pages/goods_list?query=" + e.detail.trim()
      })
      //清空输入框的值
      this.value = '';
      this.suggestList = [];
    },
    //清空历史
    removeHistory(){
      this.searchHistory = [];
      wepy.setStorageSync("searchHistory",this.searchHistory)
    }
  }
}
